package com.imagesystem.system.service.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.hutool.http.HtmlUtil;
import cn.hutool.http.webservice.SoapClient;
import com.imagesystem.common.core.domain.AjaxResult;
import com.imagesystem.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.imagesystem.system.mapper.EndoscopeInfoMapper;
import com.imagesystem.system.domain.EndoscopeInfo;
import com.imagesystem.system.service.IEndoscopeInfoService;
import com.imagesystem.common.core.text.Convert;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.http.webservice.SoapClient;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Service;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPElement;
import javax.xml.namespace.QName;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 内镜信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-11
 */
@Service
public class EndoscopeInfoServiceImpl implements IEndoscopeInfoService
{
    @Autowired
    private EndoscopeInfoMapper endoscopeInfoMapper;

    /**
     * 查询内镜信息
     *
     * @param endoscopeId 内镜信息主键
     * @return 内镜信息
     */
    @Override
    public EndoscopeInfo selectEndoscopeInfoByEndoscopeId(String endoscopeId)
    {
        return endoscopeInfoMapper.selectEndoscopeInfoByEndoscopeId(endoscopeId);
    }

    /**
     * 查询内镜信息列表
     *
     * @param endoscopeInfo 内镜信息
     * @return 内镜信息
     */
    @Override
    public List<EndoscopeInfo> selectEndoscopeInfoList(EndoscopeInfo endoscopeInfo)
    {
        return endoscopeInfoMapper.selectEndoscopeInfoList(endoscopeInfo);
    }

    /**
     * 新增内镜信息
     *
     * @param endoscopeInfo 内镜信息
     * @return 结果
     */
    @Override
    public int insertEndoscopeInfo(EndoscopeInfo endoscopeInfo)
    {
        endoscopeInfo.setCreateTime(DateUtils.getNowDate());
        return endoscopeInfoMapper.insertEndoscopeInfo(endoscopeInfo);
    }

    /**
     * 修改内镜信息
     *
     * @param endoscopeInfo 内镜信息
     * @return 结果
     */
    @Override
    public int updateEndoscopeInfo(EndoscopeInfo endoscopeInfo)
    {
        endoscopeInfo.setUpdateTime(DateUtils.getNowDate());
        return endoscopeInfoMapper.updateEndoscopeInfo(endoscopeInfo);
    }

    /**
     * 批量删除内镜信息
     *
     * @param endoscopeIds 需要删除的内镜信息主键
     * @return 结果
     */
    @Override
    public int deleteEndoscopeInfoByEndoscopeIds(String endoscopeIds)
    {
        return endoscopeInfoMapper.deleteEndoscopeInfoByEndoscopeIds(Convert.toStrArray(endoscopeIds));
    }

    /**
     * 删除内镜信息信息
     *
     * @param endoscopeId 内镜信息主键
     * @return 结果
     */
    @Override
    public int deleteEndoscopeInfoByEndoscopeId(String endoscopeId)
    {
        return endoscopeInfoMapper.deleteEndoscopeInfoByEndoscopeId(endoscopeId);
    }

    /**
     * 获取所有内镜信息
     *
     * @param endoscopeInfo 获取所有内镜信息
     * @return 结果
     */
    @Override
    public AjaxResult getAllEndoscope(EndoscopeInfo endoscopeInfo) {
        Map<String, Object> rfidNumMap = getRfidNumMap(endoscopeInfo.getRfidNum());
        Map<String, Object> maps = new HashMap<>();
        maps.put("Request", rfidNumMap);
        // TODO 更改接口地址以及调用方法
        Map<String, String> request = request("http://localhost:8890/interface?wsdl", "EndoscopeInterface", "EndoscopeInterface", maps);
        String Response = request.get("Response");
        JSONObject entries = JSONUtil.parseObj(Response);
        JSONObject str = JSONUtil.parseObj(entries.get("Body"));
        if("1".equals(str.get("resultCode"))){
            return AjaxResult.error(JSONUtil.toJsonStr(str));
        }else{
            return AjaxResult.success(JSONUtil.toJsonStr(str));
        }
    }


    public static Map<String,String> request(String url, String namespaceURl, String method, Map<String, Object> params) throws RuntimeException {
        System.out.println("=============================调用webserver接口==================================");
        try {
            SoapClient client = SoapClient.create(url)
                    .header("SOAPAction", "")
                    // 设置要请求的方法，此接口方法前缀为web，传入对应的命名空间
                    .setMethod(method, namespaceURl)
                    .setParams(params, true);
            SOAPBodyElement soapBodyElement = (SOAPBodyElement) client.getMethodEle();
            //soapBodyElement.getParentElement().getParentElement().addNamespaceDeclaration("ser", "http://services.founder.com");
            // 遍历所有子元素，查找名为"funderService"的元素
            SOAPElement funderServiceElement = null;

            for (Iterator<?> it = soapBodyElement.getChildElements(); it.hasNext();) {
                SOAPElement element = (SOAPElement) it.next();
                if (element.getLocalName().equals("funderService")) {
                    funderServiceElement = element;
                    break;
                }
            }

            if (funderServiceElement != null) {
                // 在找到的funderService元素中添加functionName属性
                funderServiceElement.addAttribute(new QName("", "functionName"), "applyfeeconfirm_orderno");
            } else {
                System.out.println("未找到名为'funderService'的元素");
            }

            Map<String, String> result  = new HashMap<>();
            result.put("param", client.getMsgStr(true));
            // 将已转义的参数还原为原始格式
            System.out.println("入参:"+ client.getMsgStr(true));
            String results = client.send(true);
            System.out.println("返回结果:"+results);

            results = HtmlUtil.unescape(results);
            result.put("result", results);

            return result;
        } catch (Exception ex) {
            throw new RuntimeException("接口连不上");
        }
    }


    public  Map<String, Object> getRfidNumMap(String RfidNum){
        // 创建最外层的Map，代表整个Request
        Map<String, Object> requestMap = new HashMap<>();

        // 创建Header部分的Map
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("SourceSystem", "内镜洗消系统");
        headerMap.put("MessageID", "GetEndoscopeInfo");

        // 创建Body部分的Map
        Map<String, Map<String, String>> bodyMap = new HashMap<>();
        Map<String, String> endoscopeInfoMap = new HashMap<>();
        // 空字符串表示查询所有内镜信息
        endoscopeInfoMap.put("RfidNum", RfidNum);

        // 将EndoscopeInfo添加到Body的Map中
        bodyMap.put("EndoscopeInfo", endoscopeInfoMap);

        // 将Header和Body添加到Request的Map中
        requestMap.put("Header", headerMap);
        requestMap.put("Body", bodyMap);
        return requestMap;
    }

}
